# author : 202213216李豆豆

import pyautogui
from pynput import mouse


# 整个程序使用with包裹代码，便于及时释放文件资源

# 鼠标移动时被调用，x,y代表函数移动到新位置的坐标
def on_move(x, y):
    with open('mouseRecorded.txt', 'a') as f:  # 参数a为追加模式打开该文件，并把打开的文件对象赋给变量f
        f.write(f'移动到:({x}, {y})\t')


# 在鼠标按钮按下或者释放时被调用，pressed传入按下还是松开的状态
def on_click(x, y, button, pressed):
    if pressed:
        with open('mouseRecorded.txt', 'a') as f:
            if button == mouse.Button.left:
                f.write(f'左键点击位置为：({x}, {y})\n')
            elif button == mouse.Button.right:
                f.write(f'右键点击位置为： ({x}, {y})\n')
            elif button == mouse.Button.middle:
                f.write(f'中键点击位置为： ({x}, {y})\n')
    else:
        with open('mouseRecorded.txt', 'a') as f:
            f.write(f'按键松开的位置：({x}, {y})\n')


# 鼠标滚动时被调用，x,y分别代表上下左右滚动的亮
def on_scroll(x, y, dx, dy):
    with open('mouseRecorded.txt', 'a') as f:
        if dy > 0:  # 向上滚动
            f.write(f'Scrolled up at ({x}, {y})\n')
        else:
            f.write(f'Scrolled down at ({x}, {y})\n')


# 鼠标拖动时调用
def on_drag(x, y):  # x,y是拖动到的新位置的坐标
    with open('mouseRecorded.txt', 'a') as f:
        f.write(f'拖动到坐标： ({x}, {y})\n')


# 使用mouse.Listener来监听鼠标时间
with mouse.Listener(
        on_move=on_move,
        on_click=on_click,
        on_scroll=on_scroll,
        on_drag=on_drag) as listener:
    listener.join()  # 保证程序不自动停止
